package com.sinog.front.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.sinog.core.domain.InterfaceLog;
import com.sinog.core.domain.JieKouLog;
import com.sinog.core.domain.UserInterFaceEntity;
import com.sinog.core.util.DateUtil;
import com.sinog.core.util.GkObjectUtils;
import com.sinog.core.util.Hex;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.asynctask.AsyncTaskLog;
import com.sinog.front.feign.basic.UserService;
import com.sinog.front.feign.biz.DataTransmissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @desc 预安置人员数据录入，方式1：http(监狱、社区矫正、看守所)
 * @author -
 * @date -
 */
@Slf4j
@RestController
public class DataTransmissionController {

    @Resource
    private DataTransmissionService dataTransmissionService;
    @Resource
    private UserService userService;
    @Autowired
    private AsyncTaskLog asyncTask;

    /**
     * 保存预安置人员 (1、主信息 2、多媒体信息 3、服刑信息 4、配偶、父母，社会关系 5、子女信息)
     * @param data data
     * @return Result
     */
    @RequestMapping(value = "/transmission/api/azbj/savePreArrangedPersonnel", method = RequestMethod.POST, produces = "application/json;charset=utf-8;")
    public Result savePreArrangedPersonnel(@RequestBody String data) {
        // 实体类对象赋值
        InterfaceLog interfaceLog = new InterfaceLog();
        JieKouLog jieKouLog = new JieKouLog();
        try {
            Map<String,Object> maps = JsonUtil.toMap(data);
            String account;
            // 实体类对象赋值--公共
            interfaceLog.setData(data);
            interfaceLog.setAccount(maps.get("account").toString());
            //将时间戳变为日期格式的字符串
            String time = DateUtil.chuoTransferDate(Long.valueOf(maps.get("time").toString()),"yyyy-MM-dd HH:mm:ss");
            interfaceLog.setTime(time);
            //sfb日志表赋值
            jieKouLog.setData(data);
            jieKouLog.setAccount(maps.get("account").toString());
            jieKouLog.setTime(time);
            StringBuilder stringBuilder = new StringBuilder(16);
            List<String> codes = new ArrayList<>(16);
            if(null != maps.get(Constants.StrFinalValue.ACCOUNT) && !"".equals(maps.get(Constants.StrFinalValue.ACCOUNT)
                                                                                   .toString())) {
                account = maps.get("account").toString();
            } else {
                account = "";
            }
            UserInterFaceEntity user = userService.getInfoByAccount(account);
            if(null == user || GkObjectUtils.isAllFieldNull(user)) {
                stringBuilder.append("接口用户不存在！");
                codes.add("800001");
                // 往日志实体类中封装数据
                interfaceLog.setCode("800001");
                interfaceLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
                jieKouLog.setCode("800001");
                jieKouLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            String unCheckField = user.getUnCheckField();
            String[] strs = unCheckField.split("\\|");
            if(StringUtils.isEmpty(unCheckField) || Constants.Number.NUM_FIVE > strs.length) {
                stringBuilder.append("配置参数错误，请联系工作人员！");
                codes.add("800002");
                // 往日志实体类中封装数据
                interfaceLog.setCode("800002");
                interfaceLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
                jieKouLog.setCode("800002");
                jieKouLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            maps.put("user",user);
            String s = JSON.toJSONString(maps);
            Result result = dataTransmissionService.savePreArrangedPersonnel(s);
            // 调用成功-往日志实体类中封装数据
            if (Constants.Number.NUM_ONE.equals(result.getCode())) {
                interfaceLog.setCode(Constants.NumberStr.NUM_STR_ONE);
                interfaceLog.setFlag(Constants.NumberStr.NUM_STR_ONE);
                jieKouLog.setCode(Constants.NumberStr.NUM_STR_ONE);
                jieKouLog.setFlag(Constants.NumberStr.NUM_STR_ONE);
            }else{
                // 保存失败的话 如check失败
                interfaceLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
                interfaceLog.setCode(result.getData().toString());
                jieKouLog.setCode(result.getData().toString());
                jieKouLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
            }
            return result;
        } catch(JSONException jsonException) {
            log.error("对外接口参数json解析失败",jsonException);
            StringBuilder stringBuilder = new StringBuilder(16);
            List<String> codes = new ArrayList<>(16);
            stringBuilder.append("json参数格式不正确，请检查！");
            codes.add("800003");
            // 往日志实体类中封装数据
            interfaceLog.setCode("800003");
            interfaceLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
            jieKouLog.setCode("800003");
            jieKouLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
            return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
        } catch(RuntimeException e) {
            log.error("对外接口发生异常",e);
            StringBuilder stringBuilder = new StringBuilder(16);
            List<String> codes = new ArrayList<>(16);
            stringBuilder.append("后台错误，请联系工作人员！");
            codes.add("800003");
            // 往日志实体类中封装数据
            interfaceLog.setCode("800003");
            interfaceLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
            jieKouLog.setCode("800003");
            jieKouLog.setFlag(Constants.NumberStr.NUM_STR_ZERO);
            return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
        } finally {
            //异步执行
            asyncTask.asyncInsertSjLog(interfaceLog);
            asyncTask.asyncInsertbjLog(jieKouLog);
        }
    }

    /**
     * 解除社区矫正接口
     * @param data 业务数据
     * @return Result
     */
    @RequestMapping(value = "/transmission/api/azbj/saveJjData", method = RequestMethod.POST, produces = "application/json;charset=utf-8;")
    public Result saveJjData(@RequestBody String data) {
        try {
            Map<String,Object> maps = JsonUtil.toMap(data);
            String account = maps.get("account").toString();
            UserInterFaceEntity user = userService.getInfoByAccount(account);
            if(null == user) {
                return Result.failure(ReturnCode.INTERFACE_USER_NOT_FOUND);
            }
            maps.put("user",user);
            String s = JSON.toJSONString(maps);
            return dataTransmissionService.saveJjData(s);
        } catch(JSONException jsonException) {
            log.error("对外接口参数json解析失败",jsonException);
            return Result.failure(5005,"参数格式不正确，请检查！",null);
        } catch(RuntimeException e) {
            log.error("对外接口发生异常",e);
            return Result.failure(ReturnCode.FAILURE);
        }
    }

    /**
     * 获取接口密钥
     * @param time 系统时间戳
     * @param account 接口账户名
     * @return Result
     */
    @RequestMapping(value = "/transmission/api/azbj/getSign", method = RequestMethod.GET)
    public Result getSign(@RequestParam String time,@RequestParam String account) {
        log.info("对外接口账号:{},时间戳:{}",account,time);
        UserInterFaceEntity user = userService.getInfoByAccount(account);
        if(null == user) {
            return Result.failure(ReturnCode.INTERFACE_USER_NOT_FOUND);
        }
        String uid = user.getUid();
        String key;
        String signature = "";
        try {
            key = Hex.genAccessKey(uid);
            //客户端自己生成密钥
            signature = Hex.genSignature(key,time,"/transmission/api/azbj/savePreArrangedPersonnel/");
        } catch(InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("对外接口生成密钥失败");
            log.error("发生异常:",e);
        }
        log.info("对外接口生成密钥：{}",signature);
        return Result.success(signature);
    }
}